package com.peng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peng.entity.Department;
import com.peng.service.DepartmentService;
import com.peng.utils.Result;
import com.peng.vo.query.DepartmentQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

@RestController
@RequestMapping("/api/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 查询部门列表
     *
     * @param departmentQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result list(DepartmentQueryVo departmentQueryVo) {
        // 调用查询部门列表方法
        List<Department> departmentList = departmentService.findDepartmentList(departmentQueryVo);
        return Result.ok(departmentList);
    }

    /**
     * 查询上级部门
     *
     * @return
     */
    @GetMapping("/parent/list")
    public Result getParentDepartment() {
        // 调用查询部门列表方法
        List<Department> departmentList = departmentService.findParentDepartment();
        return Result.ok(departmentList);
    }

    /**
     * 添加部门
     *
     * @param department
     * @return
     */
    @PreAuthorize("hasAuthority('sys:department:add')")
    @PostMapping("/add")
    public Result add(@RequestBody Department department) {
        return departmentService.save(department) ? Result.ok().message("部门添加成功") : Result.error().message("部门添加失败");
    }

    /**
     * 修改部门
     *
     * @param department
     * @return
     */
    @PreAuthorize("hasAuthority('sys:department:edit')")
    @PutMapping("/update")
    public Result update(@RequestBody Department department) {
        return departmentService.updateById(department) ? Result.ok().message("部门修改成功") : Result.error().message("部门修改失败");
    }

    /**
     * 检查部门下是否有子部门
     *
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id) {
        // 判断部门下是否有子部门
        if (departmentService.hasChildrenOfDepartment(id)) {
            return Result.exist().message("该部门下存在子部门，无法删除");
        }
        // 判断部门下是否存在用户信息
        if (departmentService.hasUserOfDepartment(id)){
            return Result.exist().message("该部门下存在用户，无法删除");
        }
        return Result.ok();
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('sys:department:edit')")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        return departmentService.removeById(id) ? Result.ok().message("删除部门成功") : Result.error().message("删除部门失败");
    }
}

